package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"news/models"
	"time"
)

type LoginControllers struct {
	beego.Controller
}

func (c *LoginControllers) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	lockKey := "lock-" + username
	num, err := models.Rdb.Exists(lockKey).Result()
	if err != nil {
		c.Data["json"] = Json{Code: 500, Msg: "系统错误"}
		c.ServeJSON()
		return
	}
	if num > 0 {
		c.Data["json"] = Json{Code: 500, Msg: "账号锁定"}
		c.ServeJSON()
		return
	}

	var user models.User
	err = models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = Json{Code: 500, Msg: "用户名错误"}
		c.ServeJSON()
		return
	}

	if user.Password == password {
		models.Rdb.Del(lockKey)
		models.Rdb.Set("count-"+username, 0, 0)
		c.Data["json"] = Json{Code: 200, Msg: "登录成功"}
		c.ServeJSON()
		return
	} else {
		countKey := "count-" + username
		count, err := models.Rdb.Get(countKey).Int() // 使用 Int() 方法将计数转换为整数。
		if err != nil {
			count = 0 // 如果出现错误，将其视为0。
		}

		if count >= 3 {
			models.Rdb.Set(lockKey, "locked", 10*time.Minute)
			c.Data["json"] = Json{Code: 500, Msg: "账号锁定"}
			c.ServeJSON()
			return
		}
		models.Rdb.Incr(countKey) //密码错误次数+1
		models.Rdb.Expire(countKey, time.Hour*24)
		c.Data["json"] = Json{Code: 500, Msg: "密码错误"}
		c.ServeJSON()
		return
	}
}
